import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

import { writeFileSync } from 'fs'
import path from 'path'
import Components from 'unplugin-vue-components/vite'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue(), myPlugin(), Components({
    // 组件所在目录（支持多个路径）
    dirs: ['src/components/tabs'],

    // 包含的文件类型
    extensions: ['vue'],
    // 自定义解析器（如需特殊命名规则）
    resolvers: [
      (name) => {
        if (name)
          return { importName: name, path: `src/components/tabs/${name}.vue` }
      }
    ]
  })],
  base: './', // 静态资源路径
})


export function myPlugin() {
  return {
    name: 'my-plugin',
    closeBundle() {
      const data = {
        version: new Date().getTime(),
      }
      writeFileSync(
        path.resolve(__dirname, 'public/config.json'),
        JSON.stringify(data)
      )
    }
  }
}


export function autoRegisterComponents(dir) {
  return {
    name: 'auto-register-components',
    configureServer(server) {
      if (server.moduleHot) {
        server.moduleHot.context().keys().forEach(server.moduleHot.accept);
      }
    },
    configResolved(config) {
      const componentsDir = path.resolve(config.root, dir);
      const files = fs.readdirSync(componentsDir);

      files.forEach(file => {
        if (file.endsWith('.vue')) {
          const filePath = path.resolve(componentsDir, file);
          const componentName = file.replace(/\.vue$/, '');
          console.log('files', componentName);
          console.log('filePath', filePath);
          const component = require(filePath).default; // 注意这里使用了ES模块的import方式

          server.app.component(componentName, component);
        }
      });
    }
  };
}